package cn.initcap.algorithm.swing.moneyexperiment;

import cn.initcap.algorithm.swing.AlgoVisHelper;
import cn.initcap.algorithm.swing.BaseAlgoFrame;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Arrays;
import java.util.Random;

/**
 * @author initcap
 * @date 2018/8/3 AM10:37
 */
public class AlgoVisualizer {

    private static int DELAY = 40;
    private int[] money;
    private BaseAlgoFrame frame;

    public AlgoVisualizer(int sceneWidth, int sceneHeight) {

        // 初始化数据
        money = new int[100];
        for (int i = 0; i < money.length; i++) {
            money[i] = 100;
        }
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new BaseAlgoFrame("Money Problem", sceneWidth, sceneHeight) {
                @Override
                public void draw(Graphics graphics) {
                    Graphics2D g2d = (Graphics2D) graphics;
                    int w = sceneWidth / money.length;
                    for (int i = 0; i < money.length; i++) {
                        if (money[i] > 0) {
                            AlgoVisHelper.setColor(g2d, AlgoVisHelper.BLUE);
                            AlgoVisHelper.fillRectangle(g2d,
                                    i * w + 1, sceneHeight / 2 - money[i], w - 1, money[i]);
                        } else {
                            AlgoVisHelper.setColor(g2d, AlgoVisHelper.RED);
                            AlgoVisHelper.fillRectangle(g2d,
                                    i * w + 1, sceneHeight / 2, w - 1, -money[i]);
                        }
                    }
                }
            };
            new Thread(() -> {
                run();
            }).start();
        });
    }

    public static void main(String[] args) {

        int sceneWidth = 1000;
        int sceneHeight = 800;

        new AlgoVisualizer(sceneWidth, sceneHeight);
    }

    public void run() {

        int x = 0;
        while (true) {
            x++;
            if (x == Integer.MAX_VALUE) {
                break;
            }

            // 改进2：是否排序
            Arrays.sort(money);
            frame.render(money);
            AlgoVisHelper.pause(DELAY);

            // 改进1：每一帧执行的轮数
            for (int k = 0; k < 50; k++) {
                for (int i = 0; i < money.length; i++) {
                    // 改进3：允许money为负值
                    int j = new Random().nextInt(money.length);
                    money[i] -= 1;
                    money[j] += 1;
                }
            }
        }
    }
}